package com.soft.springhrms.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.soft.springhrms.pojo.*;
import com.soft.springhrms.service.*;
import com.soft.springhrms.vo.AttendanceVO;
import com.soft.springhrms.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.soft.springhrms.utils.JwtUtil;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin")
@CrossOrigin
public class AdminController {
    @Autowired
    private RequestsService requestsService;
    @Autowired
    private EmployeesService employeesService;
    @Autowired
    private EmployeeChangesService employeeChangesService;
    @Autowired
    private ApprovesalaryService approvesalaryService;
    @Autowired
    private SalariesService salaryService;
    @Autowired
    private AttendanceService attendanceService;
    @Autowired
    private UsersService usersService;
    @Autowired
    private DepartmentsService departmentsService;
    @Autowired
    private PositionsService positionsService;
    @Autowired
    private SystemLogsService systemLogsService;

    @GetMapping("/dashboard")
    public ResultVO getAdminDashboard(@RequestParam String token) {
        if(!JwtUtil.isTokenValid(token)){return ResultVO.error(403,"没有权限访问");}
        DecodedJWT decodedJWT = JwtUtil.parseToken(token);
        Integer roleId = decodedJWT.getClaim("roleId").asInt();
        // 判断角色权限
        if (roleId == null || roleId != 1) {  // 如果角色不是管理员，拒绝访问
            return ResultVO.error(403, "没有权限访问此页面");
        }
        // 处理管理员的业务逻辑
        return ResultVO.success("管理员首页");
    }

    // 管理员查看员工的离职请求
    @GetMapping("/showRequests")
    public ResultVO showRequestAdmin(@RequestParam int pageNum, @RequestParam int pageSize) {
        return requestsService.queryRequestsAdmin(pageNum, pageSize);
    }

    // 管理员审批员工的离职请求
    @PostMapping("/approve")
    public ResultVO approveAdminRequest(@RequestBody Requests requests) {
        return requestsService.approveRequestsAdmin(requests);
    }

    @GetMapping("/employees")
    public ResultVO getEmployees(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(required = false, value = "keyword", defaultValue = "") String keyword) {
        IPage<Employees> IEmployees;
        try {
            System.out.println(page + "," + size + "," + keyword);
            IEmployees = employeesService.getEmployeesWithPagination(page, size, keyword);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultVO.error(404, "查询请求失败");
        }
        return ResultVO.success(IEmployees, "成功");
    }

    @PostMapping("/employees")
    public ResultVO EditEmployees(@RequestBody Employees employees) {
        System.out.println(employees.toString());
        try {
            employeesService.EditEmployees(employees);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultVO.error(404, "编辑请求失败");
        }
        return ResultVO.success();
    }
    @DeleteMapping("/employees/{userId}")
    public boolean DeleteEmployees(@PathVariable String userId){
       Users user= usersService.getById(userId);
       if(user.getRoleId()!=1&&user.getRoleId()!=2&&user.getRoleId()!=3){
           return usersService.removeById(userId);
       }
        return false;
    }
    @GetMapping("/employee_changes")
    public ResultVO getAllEmployeeChanges(
            @RequestParam(value = "page", defaultValue = "1") int page,
            @RequestParam(value = "size", defaultValue = "10") int size,
            @RequestParam(required = false, value = "keyword", defaultValue = "")String keyword){
        IPage<EmployeeChanges> IEmployeeChanges;
        try {
            IEmployeeChanges = employeeChangesService.getAllEmployeeChanges(page,size,keyword);
        } catch (Exception ex) {
            ex.printStackTrace();
            return ResultVO.error(404, "查询请求失败");
        }
        return ResultVO.success(IEmployeeChanges, "成功");
    }

    //管理员批准离职申请后同步更新员工状态和离职时间
    @PostMapping("/updateEmploymentStatus")
    public ResultVO updateEmploymentStatus(@RequestBody Map<String, Object> params) {
        return employeesService.updateEmploymentStatus(params);
    }

    //管理员查看所有工资发放申请
    @GetMapping("/getApproveSalary")
    public ResultVO getApproveSalary(@RequestParam int pageNum,
                                     @RequestParam int pageSize){

        return approvesalaryService.getAllApproveSalary(pageNum, pageSize);
    }

    //管理员审批工资发放申请

    @PostMapping("/approveSalary")
    public ResultVO ApproveSalary(@RequestBody Approvesalary approvesalary){
        return approvesalaryService.ApproveSalary(approvesalary);
    }

    //管理员批量审批工资发放申请
    @PostMapping("/batchApproveSalary")
    public ResultVO batchApproveSalary(@RequestBody List<Approvesalary> approveSalaries) {
        try {
            for (Approvesalary salary : approveSalaries) {
                approvesalaryService.ApproveSalary(salary);
            }
            return ResultVO.success("批量审批成功");
        } catch (Exception e) {
            return ResultVO.error(500,"批量审批失败: " );
        }
    }

    //管理员查看所有工资发放记录
    @GetMapping("/getAllSalaries")
    public ResultVO getAllSalaries(int pageNum, int pageSize){
        return salaryService.queryAllSalaries(pageNum, pageSize);
    }

    //管理员发起签到
    @PostMapping("/clockInRequest")
    public ResultVO clockInRequest() {
        return attendanceService.clockInRequest();
    }

    //管理员发起签退
    @PostMapping("/clockOutRequest")
    public ResultVO clockOutRequest() {
        return attendanceService.clockOutRequest();
    }

    @GetMapping("/attendanceCountRecords")
    public ResultVO getAttendanceCount(@RequestParam(value = "page", defaultValue = "1") int page,
                                       @RequestParam(value = "size", defaultValue = "8") int size){
        IPage<AttendanceVO> attendanceVOList= attendanceService.getAttendanceCount(page,size);
        System.out.println(attendanceVOList);
        return ResultVO.success(attendanceVOList,"拉取考勤记录成功");
    }
    @GetMapping("/attendance/employees")
    public ResultVO getEmployeesAsNoAttendance(@RequestParam(value = "page", defaultValue = "1") int page,
                                               @RequestParam(value = "size", defaultValue = "10") int size,@RequestParam String clockTime){
//        Date date = DateUtils.DateFormStringToDate(clockTime);
//        System.out.println(date);
        IPage<Employees> employeesList=employeesService.getEmployeesAsNoAttendance(page,size,clockTime);
        return ResultVO.success(employeesList,"成功");
    }
    @GetMapping("/getUserEcharts")
    public ResultVO getUserEcharts(){
        return usersService.getUserEcharts();
    }
    @GetMapping("/getDepartmentEcharts")
    public ResultVO getDepartmentEcharts(){
        return employeesService.getDepartmentEcharts();
    }
    @GetMapping("/getPositionEcharts")
    public ResultVO getPositionEcharts(@RequestParam(value = "departmentName") String departmentName){
        QueryWrapper queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("name",departmentName);
       Integer departmentId= departmentsService.getOne(queryWrapper).getId();

        return employeesService.getPositionEcharts(departmentId);
    }
    @GetMapping("/getAttendanceEcharts")
    public ResultVO getAttendanceEcharts(){
        return attendanceService.getAttendanceEcharts();
    }

    //管理员查看系统登录日志
    @GetMapping("/getSystemLog")
    public ResultVO loginLog(@RequestParam(value = "page", defaultValue = "1") int page,
                             @RequestParam(value = "size", defaultValue = "10") int size){
        return systemLogsService.getLogs(page,size);
    }
}

